import cv2
import numpy as np
from PIL import Image, ImageEnhance


def enhance_image(image_path):
    """
    增强图像对比度，有助于提高OCR识别精度。
    :param image_path: 输入图像的路径
    :return: 增强后的图像
    """
    img = Image.open(image_path)  # 读取图像
    enhancer = ImageEnhance.Contrast(img)  # 创建对比度增强器
    img_enhanced = enhancer.enhance(2.0)  # 提高对比度因子
    return img_enhanced


def extract_paper(image_path, extracted_paper_path):
    """
    提取纸张区域并保存为新图像。
    :param image_path: 输入图像的路径
    :param extracted_paper_path: 提取后的纸张图像保存路径
    """
    img = cv2.imread(image_path)  # 读取输入图像
    if img is None:
        print(f"无法加载图像: {image_path}")
        return None
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 转换为灰度图
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)  # 使用高斯模糊减少噪声
    edges = cv2.Canny(blurred, 50, 150)  # 使用Canny边缘检测
    kernel = np.ones((5, 5), np.uint8)  # 创建结构元素
    edges = cv2.dilate(edges, kernel, iterations=1)  # 膨胀操作
    edges = cv2.erode(edges, kernel, iterations=1)  # 腐蚀操作

    # 使用霍夫变换检测直线
    lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=100, minLineLength=100, maxLineGap=10)
    if lines is not None:
        corners = []
        for line in lines:
            x1, y1, x2, y2 = line[0]
            corners.append([x1, y1])
            corners.append([x2, y2])
        corners = np.array(corners)
        rect = cv2.minAreaRect(corners)  # 找到最小面积矩形
        box = cv2.boxPoints(rect)  # 获取矩形的四个角点
        box = np.int32(box)  # 转换为整数

        width = int(rect[1][0])  # 矩形宽度
        height = int(rect[1][1])  # 矩形高度
        src_pts = box.astype("float32")  # 转换为浮点型
        dst_pts = np.array([[0, height - 1],
                            [0, 0],
                            [width - 1, 0],
                            [width - 1, height - 1]], dtype="float32")  # 目标点

        M = cv2.getPerspectiveTransform(src_pts, dst_pts)  # 获取透视变换矩阵
        warped = cv2.warpPerspective(img, M, (width, height))  # 应用透视变换
        cv2.imwrite(extracted_paper_path, warped)  # 保存提取的纸张区域
        return
    return None


def rotate_image_180_flip(extract_image, output_path):
    """
    使用翻转方式将图片旋转180度。
    :param extract_image: 输入的图像
    :param output_path: 旋转后图像保存的路径
    """
    rotated_img = cv2.flip(extract_image, -1)  # 同时进行水平和垂直翻转
    cv2.imwrite(output_path, rotated_img)  # 保存旋转后的图片
    print(f"图片已成功旋转180度并保存为 '{output_path}'")